package model

import (
	"context"
	"time"

	"code.bydev.io/cht/customer/kyc_admin_service/internal/constant"
	"code.bydev.io/cht/customer/kyc_admin_service/internal/utils"
	"code.bydev.io/frameworks/byone/core/trace"
	"emperror.dev/errors"
	"go.opentelemetry.io/otel"
	"gorm.io/gorm"
)

const TableNameKycActionState = "kyc_action_state"

// KycActionState mapped from table <kyc_action_state>
type KycActionState struct {
	ID                   int64     `gorm:"column:id;type:bigint(20);primaryKey;autoIncrement:true;comment:ID" json:"id"`                                                                                      // ID
	MemberID             int64     `gorm:"column:member_id;type:bigint(20);index:idx_member_id,priority:1;comment:UID" json:"member_id"`                                                                      // UID
	SiteID               int32     `gorm:"column:site_id;type:smallint(6);comment:申请KYC站点(0:主站,1:韩国站,2:土耳其站)" json:"site_id"`                                                                                 // 申请KYC站点(0:主站,1:韩国站,2:土耳其站)
	ExternalUID          string    `gorm:"column:external_uid;type:varchar(64);comment:外部 UID" json:"external_uid"`                                                                                           // 外部 UID
	RecordID             string    `gorm:"column:record_id;type:varchar(64);index:idx_record_id,priority:1;comment:记录id(sumsub: applicant_id, jumio: workflow_execution_id, scanReference)" json:"record_id"` // 记录id(sumsub: applicant_id, jumio: workflow_execution_id, scanReference)
	AccountID            string    `gorm:"column:account_id;type:varchar(64);comment:账号id(sumsub:applicant_id, jumio: account_id)" json:"account_id"`                                                         // 账号id(sumsub:applicant_id, jumio: account_id)
	VerifyContent        string    `gorm:"column:verify_content;type:varchar(64);comment:认证内容，数组，以‘,’分隔" json:"verify_content"`                                                                               // 认证内容，数组，以‘,’分隔
	Level                int32     `gorm:"column:level;type:tinyint(4);comment:KYC等级(0-3)" json:"level"`                                                                                                      // KYC等级(0-3)
	Channel              int32     `gorm:"column:channel;type:tinyint(4);default:1;comment:认证通道(1:sumsub,2:jumio)" json:"channel"`                                                                            // 认证通道(1:sumsub,2:jumio)
	Action               int32     `gorm:"column:action;type:tinyint(4);comment:动作状态(0:ticket, 1:init, 2:pending, 3:complete, 4:reset)" json:"action"`                                                        // 动作状态(0:ticket, 1:init, 2:pending, 3:complete, 4:reset)
	Decision             int32     `gorm:"column:decision;type:tinyint(4);comment:最终认证结果(0:unknown,1:success,2:reject)" json:"decision"`                                                                      // 最终认证结果(0:unknown,1:success,2:reject)
	ProviderDecision     int32     `gorm:"column:provider_decision;type:tinyint(4);comment:服务商认证结果(0:unknown, 1:success, 2:reject)" json:"provider_decision"`                                                 // 服务商认证结果(0:unknown, 1:success, 2:reject)
	RejectReason         string    `gorm:"column:reject_reason;type:varchar(255);comment:最终拒绝原因" json:"reject_reason"`                                                                                        // 最终拒绝原因
	ProviderRejectReason string    `gorm:"column:provider_reject_reason;type:varchar(1024);comment:服务商拒绝原因" json:"provider_reject_reason"`                                                                    // 服务商拒绝原因
	DocType              int32     `gorm:"column:doc_type;type:tinyint(4);comment:证件大类" json:"doc_type"`                                                                                                      // 证件大类
	DocSubtype           int32     `gorm:"column:doc_subtype;type:tinyint(4);comment:证件子类" json:"doc_subtype"`                                                                                                // 证件子类
	DocNumber            string    `gorm:"column:doc_number;type:varchar(512);comment:证件号(密文)" json:"doc_number"`                                                                                             // 证件号(密文)
	Country              string    `gorm:"column:country;type:varchar(30);comment:证件签发国(KYC国籍)" json:"country"`                                                                                               // 证件签发国(KYC国籍)
	Nationality          string    `gorm:"column:nationality;type:varchar(30);comment:原籍" json:"nationality"`                                                                                                 // 原籍
	AddressCountry       string    `gorm:"column:address_country;type:varchar(30);comment:居住国" json:"address_country"`                                                                                        // 居住国
	FirstName            string    `gorm:"column:first_name;type:varchar(255);comment:名字(密文)" json:"first_name"`                                                                                              // 名字(密文)
	LastName             string    `gorm:"column:last_name;type:varchar(255);comment:姓氏(密文)" json:"last_name"`                                                                                                // 姓氏(密文)
	Dob                  string    `gorm:"column:dob;type:varchar(128);comment:出生日期(密文)" json:"dob"`                                                                                                          // 出生日期(密文)
	IdempotentID         string    `gorm:"column:idempotent_id;type:varchar(64);uniqueIndex:uk_idempotent_id,priority:1;index:uniq_idempotent_id,priority:1;comment:幂等id" json:"idempotent_id"`               // 幂等id
	ReviewTime           int64     `gorm:"column:review_time;type:bigint(20);comment:验证时间(时间戳 ms)" json:"review_time"`                                                                                        // 验证时间(时间戳 ms)
	ProviderCreateAt     int64     `gorm:"column:provider_create_at;type:bigint(20);index:idx_provider_create_at,priority:1;comment:供应商回调时间(时间戳 ms)" json:"provider_create_at"`                               // 供应商回调时间(时间戳 ms)
	CreatedAt            time.Time `gorm:"column:created_at;type:datetime;default:CURRENT_TIMESTAMP;comment:记录创建时间" json:"created_at"`                                                                        // 记录创建时间
	UpdatedAt            time.Time `gorm:"column:updated_at;type:datetime;default:CURRENT_TIMESTAMP;comment:记录更新时间" json:"updated_at"`                                                                        // 记录更新时间
	DocDetail            string    `gorm:"column:doc_detail;type:text;comment:证件详情，JSON(密文)" json:"doc_detail"`                                                                                               // 证件详情，JSON(密文)
	IssuingDate          time.Time `gorm:"column:issuing_date;type:date;comment:签发日期" json:"issuing_date"`                                                                                                    // 签发日期
	ExpireDate           time.Time `gorm:"column:expire_date;type:date;comment:有效期" json:"expire_date"`                                                                                                       // 有效期
	FaceDetail           string    `gorm:"column:face_detail;type:text;comment:人脸详情，JSON(密文)" json:"face_detail"`                                                                                             // 人脸详情，JSON(密文)
	AddressDetail        string    `gorm:"column:address_detail;type:text;comment:地址详情，JSON(密文)" json:"address_detail"`                                                                                       // 地址详情，JSON(密文)
	ClientDetail         string    `gorm:"column:client_detail;type:text;comment:客户端详情，JSON" json:"client_detail"`                                                                                            // 客户端详情，JSON
	SerialType           int32     `gorm:"column:serial_type;type:tinyint(4);not null;comment:证件序列类型(0:第一证件;1:第二证件)" json:"serial_type"`                                                                      // 证件序列类型(0:第一证件;1:第二证件)
	IsTransfer           int32     `gorm:"column:is_transfer;type:tinyint(4);not null;comment:KYC转移标记(0:非转移;1:转入;2:转出)" json:"is_transfer"`                                                                   // KYC转移标记(0:非转移;1:转入;2:转出)
	SelectDocType        int32     `gorm:"column:select_doc_type;type:tinyint(4);not null;comment:选择证件类型(0:Unspecified;1:ID;2:PP;3:DL;4:RP;5:Bill;33:BVN)" json:"select_doc_type"`                            // 选择证件类型(0:Unspecified;1:ID;2:PP;3:DL;4:RP;5:Bill;33:BVN)
	SelectCountry        string    `gorm:"column:select_country;type:varchar(4);not null;comment:用户选择国家(3字码)" json:"select_country"`                                                                          // 用户选择国家(3字码)
	BusinessID           string    `gorm:"column:business_id;type:varchar(16);not null;comment:业务来源(global:Platform;card:Card;nft:NFT;faas:Yeeha)" json:"business_id"`                                        // 业务来源(global:Platform;card:Card;nft:NFT;faas:Yeeha)
}

// TableName KycActionState's table name
func (*KycActionState) TableName() string {
	return TableNameKycActionState
}

// GetLatestApprovedOnboardPOIRecord 获取最新的通过的onboard poi记录
func (t *KycActionState) GetLatestApprovedOnboardPOIRecord(ctx context.Context, memberID int64) (*KycActionState, error) {
	ctx, span := otel.Tracer(trace.TracerName).Start(ctx, utils.GetPFuncName())
	defer span.End()

	db := DBKyc(ctx)
	record := &KycActionState{}
	err := db.
		Where("member_id = ?", memberID).
		Where("level = ?", constant.KYCLevel1).
		Where("decision = ?", constant.KYCDecisionSuccess).
		Where("serial_type = ?", constant.KYCVerificationOnboarding).
		Order("provider_create_at DESC").
		Take(record).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, err
	}
	return record, nil
}

func (t *KycActionState) GetAllApprovedSupplementPOIRecord(ctx context.Context, memberID int64) ([]*KycActionState, error) {
	ctx, span := otel.Tracer(trace.TracerName).Start(ctx, utils.GetPFuncName())
	defer span.End()

	db := DBKyc(ctx)
	var records = make([]*KycActionState, 0)
	err := db.
		Where("member_id = ?", memberID).
		Where("level = ?", constant.KYCLevel1).
		Where("decision = ?", constant.KYCDecisionSuccess).
		Where("serial_type = ?", constant.KYCVerificationSupplement).
		Order("provider_create_at DESC").
		Find(&records).Error
	if err != nil {
		return nil, err
	}
	return records, nil
}
